import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormsModule } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MessageService } from 'src/app/service/message.service';
import { User } from 'src/app/model/user';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username: string
  password: string
  captcha: string
  headers = new HttpHeaders({ 'Content-Type': 'application/json' })
  constructor(private http: HttpClient,
    private messageService: MessageService) { }


  loginForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl(''),
    captcha: new FormControl('')
  })

  ngOnInit(): void {
  }

  onSubmit(): void {
    console.log('this.profileForm.value', this.loginForm.value)
    // debugger
    this.http.post<any>('/api/user/login',
      this.loginForm.value,
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log(data)
        if (data.status == 'success') {
          localStorage.setItem('userinfo', JSON.stringify(data.data))
          setTimeout(() => {
            window.location.assign('/')
          }, 1000);
        } else if (data.status == 'codefail') {
          alert('Captcha is wrong')
          this.refresh()
          this.captcha = ''
        } else {
          alert('username or password is wrong')
          // this.username = ''
          // this.password = ''
          // window.location.assign('/login')
        }
      });
    // this.http.get('/api/services')
    //   .subscribe(data => {
    //     console.log(data)
    //   })
  }

  reset(): void {
    console.log('reset')
    this.loginForm.reset()
  }

  refresh(): void {
    console.log('refresh')
    let captcha_img = <HTMLInputElement>document.getElementById('captcha_img')
    captcha_img.src = "/api/kaptcha?" + Math.random()
  }
}
